$(document).ready(function() {
  $("#dialog").dialog({
  	autoOpen: false,
  	modal: true,
  	width: 450,
  	buttons: {
  		OK: function() {
  			$(this).dialog('close');
  			$("#dialog > .ui-widget > .ui-corner-all").removeClass('ui-state-highlight');
  			$("#dialog > .ui-widget > .ui-corner-all > p > .ui-icon").removeClass('ui-icon-check');
  			$("#dialog > .ui-widget > .ui-corner-all").removeClass('ui-state-error');
  			$("#dialog > .ui-widget > .ui-corner-all > p > .ui-icon").removeClass('ui-icon-alert');
  		}
  	}
  });
 
	var options = {
		success: processResponse,
		dataType: 'json'
	}; 

	$('form').submit(function() {
		$(this).ajaxSubmit(options);
		return false; 
	});
});

function processResponse(resp)
{
	$("#dialogMessage").text(resp.message);
	$("ul.ui-state-error-text").remove();
	switch(resp.code)
	{
		case 200:
			$("#dialog > .ui-widget > .ui-corner-all").addClass('ui-state-highlight');
			$("#dialog > .ui-widget > .ui-corner-all > p > .ui-icon").addClass('ui-icon-check');
			if (resp.return_url)
			{
				setTimeout(function(){window.location.href = resp.return_url}, 1000);
			}
			break;
		case 406:			
			for (field_name in resp.data)
			{
			  html = "<ul class='ui-state-error-text'>";
				for (rule in resp.data[field_name])
				{
					html += "<li>" + resp.data[field_name][rule] + "</li>";
				}
				html += "</ul>";
				fieldItem = $("*[name='"+field_name+"']");
				if (0 == fieldItem.length)
				{
				  fieldItem = $("*[name='"+field_name+"\[\]']");
				}
				fieldItem.parent().append(html);
			}
			$("#dialog > .ui-widget > .ui-corner-all").addClass('ui-state-error');
			$("#dialog > .ui-widget > .ui-corner-all > p > .ui-icon").addClass('ui-icon-alert');
			break;
		default:
			$("#dialog > .ui-widget > .ui-corner-all").addClass('ui-state-error');
			$("#dialog > .ui-widget > .ui-corner-all > p > .ui-icon").addClass('ui-icon-alert');
	}
	$("#dialog").dialog('open');
}
